package it.storm.solution;

import java.util.ArrayList;
import java.util.List;

/**
 * 1472. 设计浏览器历史记录
 * https://leetcode-cn.com/problems/design-browser-history/
 */
public class Solutions_1472 {
    public static void main(String[] args) {
        BrowserHistory browserHistory = new BrowserHistory("leetcode.com");
        browserHistory.visit("google.com");
        browserHistory.visit("facebook.com");
        browserHistory.visit("youtube.com");
        String res1 = browserHistory.back(1);  // output: "facebook.com"
        String res2 = browserHistory.back(1);  // output: "google.com"
        String res3 = browserHistory.forward(1);  // output: "facebook.com"
        browserHistory.visit("linkedin.com");
        String res4 = browserHistory.forward(2);  // output: "linkedin.com"
        String res5 = browserHistory.back(2);  // output: "google.com"
        String res6 = browserHistory.back(7);  // output: "leetcode.com"
        System.out.println("");
    }
}

class BrowserHistory {
    List<String> list;
    // 记录当前所访问的索引
    int curIdx = -1;
    // 记录能够前进到的最大索引
    int maxIdx;

    public BrowserHistory(String homepage) {
        list = new ArrayList<>();
        visit(homepage);
    }

    public void visit(String url) {
        // 回退后进行 visit 时，再 forward 将无法前进（当前就是最后一步）
        ++ curIdx;
        if (curIdx > list.size() - 1) {
            // 新增
            list.add(url);
        } else {
            // 赋值
            list.set(curIdx, url);
        }
        maxIdx = curIdx;
    }

    public String back(int steps) {
        // 不够回退 steps 步时，回退到 0
        curIdx = Math.max(curIdx - steps, 0);
        return list.get(curIdx);
    }

    public String forward(int steps) {
        // 不够前进 steps 步时，前进到 limit - 1
        curIdx = Math.min(curIdx + steps, maxIdx);
        return list.get(curIdx);
    }
}
